import React, { useEffect, useState } from 'react'
import { withRouter } from 'react-router-dom'
import {getSidelist} from '../../api/boxApi'
//导入connect方法
import { connect } from 'react-redux'

import './sidemenu.scss'
import {
    HomeOutlined,
    UserOutlined,
    EyeInvisibleOutlined,
    FileTextOutlined,
    RocketOutlined,
    HighlightOutlined
} from '@ant-design/icons';

import { Layout, Menu } from 'antd';
const { Sider } = Layout;
const { SubMenu } = Menu

// 图标映射
const iconList = {
    '/home': <HomeOutlined />,
    '/user-manage': <UserOutlined />,
    '/right-manage': <EyeInvisibleOutlined />,
    '/news-manage': <FileTextOutlined />,
    '/audit-manage': <HighlightOutlined />,
    '/publish-manage': <RocketOutlined />
}

// 组件
function SideMenu(props) {
    const [meun, setMeun] = useState([])
    // 从token中获取权限列表
    const {role:{rights}} = JSON.parse(localStorage.getItem("token"))
    //获取侧边栏数据
    useEffect(() => {

        getSidelist().then((res) => {
                setMeun(res.data)
            })
    }, [])
    
    const checkPagePermission = (item) => {
        if (item.pagepermisson === 1 && rights.includes(item.routeKey)) {
            return true
        } else {
            return false
        }
    }
    // 菜单元素
    const renderMenu = (menuList) => {
        return menuList.map(item => {
            if (item.children?.length > 0 && checkPagePermission(item)) {
                return <SubMenu key={item.routeKey} icon={iconList[item.routeKey]} title={item.title}>
                    {renderMenu(item.children)}
                </SubMenu>
            }
            return checkPagePermission(item) && <Menu.Item key={item.routeKey} icon={iconList[item.routeKey]} onClick={() => {
                props.history.push(item.routeKey)
            }}>{item.title}</Menu.Item>
        })
    }
    return (
        <Sider trigger={null} collapsible collapsed={props.sidebarReducer}>
            <div style={{ display: "flex", height: "100%", "flexDirection": "column" }}>
                {props.sidebarReducer? <></>:<div className="logo" >文章发布管理系统</div>}
                
                <div style={{ flex: 1, "overflow": "auto" }}>
                    <Menu theme="dark" mode="inline"
                        selectedKeys={[props.location.pathname]}
                        defaultOpenKeys={["/"+props.location.pathname.split("/")[1]]}
                    >
                        {renderMenu(meun)}
                    </Menu>
                </div>
            </div>
        </Sider>
    )
}
/*
 connect(
  // mapStateToProps  
  // mapDispatchToProps
 )(被包装的组件)
*/
const mapStateToProps = (state) => { 
    return ({
        sidebarReducer:state.sidebarReducer.isCollapsed
    })
}

export default connect(mapStateToProps)(withRouter(SideMenu))